package cn.itcast.controller;

import cn.itcast.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;


@RestController
public class MovieController {
  @Autowired
  private RestTemplate restTemplate;
  @Autowired
  private LoadBalancerClient loadBalancerClient;

  @GetMapping("/movie/{id}")
  public User findById(@PathVariable Long id) {
    // http://localhost:7900/simple/
    // VIP virtual IP
    // HAProxy Heartbeat
    return this.restTemplate.getForObject("http://car-manager-user/simple/" + id, User.class);
  }

  @GetMapping("/test")
  public String test(){
    ServiceInstance serviceInstance=this.loadBalancerClient.choose("car-manager-user");
    System.out.println(serviceInstance.getHost()+serviceInstance.getServiceId()+serviceInstance.getPort());

    ServiceInstance serviceInstance2=this.loadBalancerClient.choose("car-manager-user2");
    System.out.println(serviceInstance2.getHost()+serviceInstance2.getServiceId()+serviceInstance2.getPort());
    return "1";
  }

  /**
   * commandProperties = @HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE") 表示在同一个线程池中
   * @return
   */
  @GetMapping("/list-all")
  @HystrixCommand(fallbackMethod = "findByIdFallback",commandProperties = @HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE"))
  public List<User> listAll(){
    return restTemplate.getForObject("http://car-manager-user/list-all/",List.class);
  }

    /**
     * Hystrix 容错的方法
     * @return
     */
    public List<User> findByIdFallback(){
      List<User> s=new ArrayList<>();
      User user=new User();
      user.setName("进入容错");
      s.add(user);
      return s;
    }
}
